import Api from '@/api/manager'
import {getToken, removeToken, setToken} from '@/utils/auth'
import {resetRouter} from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    constants: [],
    limit: {
      docker: 0,
      ssh: 0
    }
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_CONSTANTS: (state, constants) => {
    state.constants = constants
  },
  SET_LIMIT: (state, limit) => {
    state.limit = limit
  }
}

const actions = {
  // user login
  login({commit}, userInfo) {
    return new Promise((resolve, reject) => {
      Api.login(userInfo).then(response => {
        const {data} = response
        console.log(data);
        commit('SET_TOKEN', data.token)
        commit('SET_LIMIT', data.limit)
        setToken(data.token)
        localStorage.setItem('menus', JSON.stringify(data.permissions));
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      Api.getInfo().then(response => {
        const {data} = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        const {name} = data
        commit('SET_NAME', name)
        commit('SET_LIMIT', data.limit)
        localStorage.setItem('menus', JSON.stringify(data.permissions));
        localStorage.setItem("myId", data.id)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      Api.logout(state.token).then(() => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resetRouter()
        localStorage.removeItem('menus');
        localStorage.removeItem("myId")
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

